package com.tajiang.business.search.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.tajiang.business.R;
import com.tajiang.business.common.adapter.EmptyViewAdapter;
import com.tajiang.business.common.dialog.DialogWithTwoButton;
import com.tajiang.business.common.fragment.BaseFragment;
import com.tajiang.business.common.utils.BottomCallBackInterface;
import com.tajiang.business.common.utils.PostDataTools;
import com.tajiang.business.model.Order;
import com.tajiang.business.model.Pager;
import com.tajiang.business.order.adapter.OrderMenuListAdapter;
import com.tajiang.business.order.view.OrderLoadMoreFooterView;
import com.tajiang.business.order.view.OrderRefreshHeadView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 订单查询
 * Created by Administrator on 2016/5/10.
 */
public class SearchFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.et_search_input)
    EditText etSearchInput;

    @BindView(R.id.swipe_refresh_header)
    OrderRefreshHeadView swipeRefreshHeader;

    @BindView(R.id.swipe_target)
    RecyclerView listView;

    @BindView(R.id.swipe_load_more_footer)
    OrderLoadMoreFooterView swipeLoadMoreFooter;

    @BindView(R.id.swipe_to_load_layout)
    SwipeToLoadLayout swipeToLoadLayout;

    private String searchContent = ""; //搜索订单

    private EmptyViewAdapter emptyViewAdapter;
    private OrderMenuListAdapter mAdapter;

    private List<Order> orderList = new ArrayList<Order>();
    private int pageNumber = 1;//当前页

    @Override
    protected void initTopBar() {
        setTitle("订单查询");
    }

    @Override
    protected void initLayout() {

        setContentView(R.layout.fragment_search);

        etSearchInput.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                searchContent = charSequence.toString();
                onRefresh();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //支持搜索框上弹出软键盘回车搜索
        etSearchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //TODO.....搜索....订单........
                    searchContent = etSearchInput.getText().toString();

                    onRefresh();
                    return true;
                }

                return false;
            }
        });
    }

    @Override
    protected void initData() {

        etSearchInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearchInput.setCursorVisible(true);
            }
        });

        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        swipeToLoadLayout.setLoadMoreEnabled(false);

        mAdapter = new OrderMenuListAdapter(getActivity(), Order.ORDER_QUERY, orderList, new BottomCallBackInterface.OnBottomClickListener() {

            @Override
            public void onBottomClick(View v, int position) {

                final Order order = orderList.get(position);
                if(v.getId() == R.id.item_order_menu_img_time){

                }else if(v.getId() == R.id.item_order_menu_phone){

                    DialogWithTwoButton.showDialog(getActivity(), "取消", "确认", "确认拨打电话: " + order.getReceiverPhone(), new DialogWithTwoButton.DialogCallback() {

                        @Override
                        public void callback(int position) {

                            if(position == 1){

                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + order.getReceiverPhone()));
                                startActivity(intent);
                            }
                        }
                    });
                }
            }
        });

        listView.setLayoutManager(new LinearLayoutManager(getActivity()));
        listView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext())
                .color(getResources().getColor(R.color.gray)).size(36).build());
        listView.setItemAnimator(new DefaultItemAnimator());

        emptyViewAdapter = new EmptyViewAdapter(getContext(), R.layout.layout_empty_order_view);

        listView.setAdapter(emptyViewAdapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();

        onRefresh();
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {

        pageNumber = 1;
        PostDataTools.order_list(getActivity(), Order.ORDER_QUERY, searchContent, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<Order> pager = (Pager<Order>) object;
                List<Order> newOrderList = pager.getList();

                orderList.clear();
                orderList.addAll(newOrderList);

                updateMyRecyclerView(orderList);

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    pageNumber = 2;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }
            }
        });
    }

    /**
     * 上拉加载更多
     */
    @Override
    public void onLoadMore() {

        PostDataTools.order_list(getActivity(), Order.ORDER_QUERY, searchContent, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<Order> pager = (Pager<Order>) object;
                List<Order> newOrderList = pager.getList();

                orderList.addAll(newOrderList);
                mAdapter.notifyDataSetChanged();

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    ++pageNumber;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }else{
                    swipeToLoadLayout.setLoadMoreEnabled(false);
                }
            }
        });
    }

    private void updateMyRecyclerView(List<Order> newOrderList) {

        if (newOrderList.size() < 1) {
            swipeToLoadLayout.setLoadMoreEnabled(false);
            listView.setAdapter(emptyViewAdapter);
        } else {
            swipeToLoadLayout.setLoadMoreEnabled(true);
            listView.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
        }
    }

    //刷新今日已打印订单。和有效订单
    @Override
    public void reFreshCurrentPageData() {
        super.reFreshCurrentPageData();

        onRefresh();
    }
}